
let sdk = window['sdk'] = window['sdk'] ? window['sdk'] : {}
/**
广告样式	最小尺寸（宽*高）
左图右文、左文右图	720*300
上图下文、下图上文	720*630
横版纯图	720*525
 */

class VivoSDK {

    constructor() {

    }
    p;
    init(p, config) {
        this.p = p ? p : window['qg'];
        this.config = config;
        this.vedioAd = {}
        console.log('this.config  ', this.config)
        console.log('this.rewardedAd  ', this.vedioAd)
        // this.showToast('sdk初始化成功')
    }

    showToast(message) {
        this.p.showToast({
            message: message
        })
    }
    getShare() {
        return null;
    }


    showGridAd(index, param) {

    }

    showMultipleGridAd(index, param) {
        this.showBoxBannerAd(index)
    }

    hideMultipleGridAd(index) {
        this.hideBoxBannerAd()
    }

    closeMultipleGridAd(index) {
        this.closeBoxBannerAd()
    }

    showMatrixAd(index, param) {
        this.showBoxPortalAd(index, param)
    }

    closeMatrixAd() {
        this.closeBoxPortalAd()
    }


    getCustomAdSize(design) {
        let size = sdk.getVisibleSize()
        // let r = size.height > size.width
        var defaultSize = (size.height / size.width) ? { height: design.width, width: design.height } : { width: design.width, height: design.height }
        let width = design.height * ((size.height / size.width) > (defaultSize.height / defaultSize.width) ? size.width / defaultSize.width : size.height / defaultSize.height);
        return width;
    }

    getCustomAdStyle(param) {
        // let ratio = CustomAdRatio[param.type]
        // let _dir = param.dir;
        // let r = param.style.width / param.style.height;
        let sys = this.p.getSystemInfoSync()
        // let width = this.getCustomAdSize(ratio.design);
        // let height = width / r;
        // param.style.width = width;
        // param.style.height = height;
        let style = sdk.getRealStyle(param.style, sys)
        console.log(' style ', style)
        return style;

    }
    createCustomAd(index, param) {
        if (!this.p.createCustomAd) {
            return;
        }
        let ad = this.getAd(sdk.ADName.CustomAd, index)
        if (!ad) {
            return;
        }
        let customAd = this.p.createCustomAd({
            posId: ad,
            style: this.getCustomAdStyle(param),
        });
        customAd.onError(() => {

        })
        return customAd;
    }
    hideCustomAd(index) {
        if (this.customAd) {
            this.customAd.hide();
        }
    }

    showCustomAd(index, param, func) {
        let dir = 0;
        let callback = null
        if (func) {//向后兼容。
            dir = param;
            callback = func
        } else {
            dir = param.dir;
            callback = param.callback;
        }
        if (this.customAd) {
            this.customAd.destroy();
            this.customAd = null;
        }
        this.customAd = this.createCustomAd(index, param)
        if (this.customAd) {
            this.customAd.show().then(() => {
                console.log('原生模板广告展示完成');
                if (callback) {
                    callback(sdk.ResultState.YES)
                }
            }).catch((err) => {
                console.log('原生模板广告展示失败', JSON.stringify(err));
                if (callback) {
                    callback(sdk.ResultState.NO)
                }
            })
        }
    }

    createInsertAd(index) {
        if (!this.p.createInterstitialAd) {
            return;
        }
        let ad = this.getAd(sdk.ADName.InsertAd, index)
        if (!ad) {
            return;
        }
        const interstitialAd = this.p.createInterstitialAd({
            posId: ad
        });
        interstitialAd.onError(err => {
            console.log("插屏广告加载失败", err);
        });
        return interstitialAd
    }

    showInsertAd(index) {
        this.interstitialAd = this.createInsertAd(index)
        if (this.interstitialAd) {
            this.interstitialAd.show().then(() => {
                console.log('插屏广告展示完成');
            }).catch((err) => {
                console.log('插屏广告展示失败', err);
            })
        }
    }

    exitApplication() {
        this.p.exitApplication()
    }

    closeInsertAd(index) {

    }

    preloadRewaredAd(index) {
        let ad = this.createRewaredAd(index)
        if (ad) {
            this.vedioAd[index] = { ad: ad, callback: null, state: 0, autoPlay: false }
        }
    }
    createRewaredAd(index) {
        if (!this.p.createRewardedVideoAd) {
            return;
        }
        let ad = this.getAd(sdk.ADName.RewaredAd, index)
        if (!ad) {
            return;
        }
        const rewardedAd = this.p.createRewardedVideoAd({
            posId: ad,
        });
        rewardedAd.onError(err => {
            console.log("激励视频广告加载失败", err);
            this.showToast('激励视频广告加载失败')
            let obj = this.vedioAd[index]
            if (obj) {
                if (obj.callback) {
                    obj.callback(sdk.ResultState.NO)
                }
            }

        });
        rewardedAd.onLoad((res) => {
            console.log('激励视频广告加载完成-onload触发', JSON.stringify(res));
            let obj = this.vedioAd[index]
            if (obj) {
                obj.state = 1;
                if (obj.autoPlay) {
                    this.rewaredShow(obj)
                }
            }
        })
        const func = (res) => {
            console.log('视频广告关闭回调')
            let obj = this.vedioAd[index]
            if (obj.callback) {
                if (res && res.isEnded) {
                    console.log("正常播放结束，可以下发游戏奖励");
                    obj.callback(sdk.ResultState.YES)
                } else {
                    obj.callback(sdk.ResultState.NO)
                    console.log("播放中途退出，不下发游戏奖励");
                }
            }

        }
        rewardedAd.onClose(func);
        return rewardedAd;
    }

    rewaredShow(obj) {
        obj.autoPlay = false;
        obj.state = 0;
        obj.ad.show().then(() => {
            console.log('激励视频广告展示完成');
        }).catch((err) => {
            console.log('激励视频广告展示失败', JSON.stringify(err));
            this.showToast('激励视频广告展示失败')
        })
    }

    loadRewaredAd(index) {
        if (!this.vedioAd[index]) {
            let ad = this.createRewaredAd(index);
            if (ad) {
                this.vedioAd[index] = { ad: ad, callback: null, state: 0, autoPlay: false }
            }
        } else {
            if (this.vedioAd[index]) {
                this.vedioAd[index].ad.load();
            }
        }
    }

    showRewaredAd(index, callback) {
        console.log(' this.rewardedAdd ', this.vedioAd)
        let obj = this.vedioAd[index];
        if (!obj) {
            let ad = this.createRewaredAd(index);
            if (ad) {
                this.vedioAd[index] = { ad: ad, callback: callback, state: 0, autoPlay: true }
            }

        } else {
            obj.callback = callback;
            if (obj.state == 0) {
                obj.autoPlay = true;
                obj.ad.load();
            } else {
                this.rewaredShow(obj)
            }

        }

    }




    loadBannerAd(index, data) {
        this.bannerAd = this.createBannerAd(index)
    }

    //param:{dir:number,left:number,top:number}
    // dir 0:down,1:up
    createBannerAd(index, param) {
        if (!this.p.createBannerAd) {
            return;
        }
        //style内无需设置任何字段，banner会在屏幕底部居中显示，
        // 没有style字段，banner会在上边显示
        // 1053以及以上版本支持属性设置
        let ad = this.getAd(sdk.ADName.BannerAd, index)
        if (!ad) {
            return;
        }
        var bannerAd = null;
        switch (param.dir) {
            case sdk.SDKDir.BOTTOM_MID:
                bannerAd = this.p.createBannerAd({
                    posId: ad,
                    style: {}
                });
                break;
            case sdk.SDKDir.TOP_MID:
                bannerAd = this.p.createBannerAd({
                    posId: ad
                });
                break;
            default:
                bannerAd = this.p.createBannerAd({
                    posId: ad,
                    style: {}
                });
                break;
        }
        bannerAd.onError(err => {
            console.log("banner广告加载失败", err);
        });
        bannerAd.onClose(() => {
            console.log("banner广告onClose");
        })
        return bannerAd;
    }

    showBannerAd(index, param) {
        this.closeBannerAd()
        if (!this.bannerAd) {
            this.bannerAd = this.createBannerAd(index, param)
        }
        if (this.bannerAd) {
            this.bannerAd.show().then(() => {
                console.log('banner广告展示完成');
            }).catch((err) => {
                console.log('banner广告展示失败', JSON.stringify(err));
            })
        }
    }

    hideBannerAd() {
        if (this.bannerAd) {
            this.bannerAd.hide()
        }
    }

    closeBannerAd() {
        if (this.bannerAd) {
            this.bannerAd.destroy()
            this.bannerAd = null;
        }
    }

    getAd(name, index) {
        if (this.config.ads) {
            let cfg = this.config.ads[name];
            if (!cfg) {
                return;
            }
            let ids = cfg.ids;
            if (!ids) {
                return;
            }
            let ad = ids[index]
            return ad;
        } else {//为了向下兼容
            let cfg = this.config[name];
            if (!cfg) {
                return;
            }
            let ads = cfg.ads;
            if (!ads) {
                return;
            }
            let ad = ads[index]
            return ad;
        }

    }

    createBoxBannerAd(index) {
        if (this.p.createBoxBannerAd) {
            let ad = this.getAd(sdk.ADName.BoxBannerAd, index)
            if (!ad) {
                return;
            }
            let boxBannerAd = this.p.createBoxBannerAd({
                posId: ad
            })
            boxBannerAd.onError(function (err) { console.log("盒子横幅广告加载失败", err) })
            return boxBannerAd;
        } else {
            console.log('暂不支持互推盒子相关 API')
            return null;
        }
    }

    // 结算页、游戏开始页等适合展示的场景调用
    showBoxBannerAd(index) {
        this.closeBoxBannerAd()
        if (!this.boxBannerAd) {
            this.boxBannerAd = this.createBoxBannerAd(index)
        }
        if (this.boxBannerAd) {
            // 广告数据加载成功后展示
            this.boxBannerAd.show().then(function () {
                console.log('show success')
            }).catch(function (error) {
                console.log('show fail with:' + error.errCode + ',' + error.errMsg)
            })
        }
    }

    hideBoxBannerAd() {
        if (this.boxBannerAd) {
            this.boxBannerAd.hide().then(function () {
                console.log('hide success')
            }).catch(function (error) {
                console.log('hide fail with:' + error.errCode + ',' + error.errMsg)
            })
        }
    }

    // 场景切换等需要关闭时调用
    closeBoxBannerAd() {
        if (this.boxBannerAd) {
            this.boxBannerAd.destroy()
            this.boxBannerAd = null;
        }
    }

    createBoxPortalAd(index, param) {

        if (this.p.createBoxPortalAd) {
            let ad = this.getAd(sdk.ADName.BoxPortalAd, index)
            if (!ad) {
                return;
            }
            let marginTop = 200;
            let image = ''
            if (param) {
                if (param.marginTop != undefined) {
                    marginTop = param.marginTop
                }
                if (param.image) {
                    image = param.image
                }
            }
            let boxPortalAd = this.p.createBoxPortalAd({
                posId: ad,
                image: image,
                marginTop: marginTop
            })
            boxPortalAd.onError(function (err) {
                console.log("盒子九宫格广告加载失败", err)
            })
            boxPortalAd.onClose(function () {
                console.log('close')
                if (boxPortalAd.isDestroyed) {
                    return
                }
                // 当九宫格关闭之后，再次展示Icon
                boxPortalAd.show()
            })
            return boxPortalAd;

        } else {
            console.log('暂不支持互推盒子相关 API')
            return null;
        }
    }

    // 游戏首页等适合展示Icon的场景常驻展示（每次回到此页面均调用一次）
    showBoxPortalAd(index) {
        this.closeBoxPortalAd();
        if (!this.boxPortalAd) {
            this.boxPortalAd = this.createBoxPortalAd(index)
        }
        if (this.boxPortalAd) {
            // 广告数据加载成功后展示
            this.boxPortalAd.show().then(function () {
                console.log('show success')
            })
        }
    }
    // 场景切换等需要关闭时调用
    closeBoxPortalAd() {
        if (this.boxPortalAd) {
            this.boxPortalAd.isDestroyed = true
            this.boxPortalAd.destroy()
            this.boxPortalAd = null;
        }
    }

}

window['vivo_sdk'] = VivoSDK;